from django.http import HttpResponse ,HttpResponseRedirect
from django.template import RequestContext, loader
from django.utils import simplejson
from social.models import *
from django.db.models import Q
import re
import json

def autocompleteModel(request):
    usersInDB = User.objects.filter(Q(firstName__startswith=request.REQUEST['search']) |
                                    Q(lastName__startswith=request.REQUEST['search']))
    results = []
    if not usersInDB:
        resp = request.REQUEST['callback'] + '(' + '[""]' + ');'
        return HttpResponse(resp, content_type='application/json')
    for member in usersInDB:
        results.append(member.firstName)
    resp = request.REQUEST['callback'] + '(' + simplejson.dumps(results) + ');'
    return HttpResponse(resp, content_type='application/json')


def registerSubmitModel(request):
    response = {"fn": 0, "ln": 0, "email": 0, "pass": 0}
    firstName = request.REQUEST['firstName']
    lastName = request.REQUEST['lastName']
    emailAddress = request.REQUEST['emailAddress']
    password = request.REQUEST['password']

    isFirstNameAccepted = re.match(r'^[a-zA-Z0-9_]*$', firstName)
    isLastNameAccepted = re.match(r'^[a-zA-Z0-9_]*$', lastName)
    isEmailAccepted = re.match(r'^[a-zA-Z0-9_.+]+@[a-zA-Z0-9_.+]+\.[a-zA-Z0-9_.+]+$', emailAddress)
    response["fn"] = int(bool(int(bool(isFirstNameAccepted)) and len(firstName)))
    response["ln"] = int(bool(int(bool(isLastNameAccepted)) and len(lastName)))
    response["email"] = int(bool(int(bool(isEmailAccepted)) and len(emailAddress)))
    response["pass"] = (1 if(len(password) >= 6) else 0)
    if response["email"]:
        if User.objects.filter(email=emailAddress):
            response["email"] = 2
    return HttpResponse(json.dumps(response), content_type='application.json')